--
-- Ace Addon Object
--

local AspireML = LibStub("AceAddon-3.0"):NewAddon("AspireML", "AceConsole-3.0", "AceEvent-3.0")
_G.AspireML = AspireML

--
-- Upvalues
--
local _G = _G
local pairs, ipairs, format = pairs, ipairs, format
local string, gsub = string, gsub

--
-- Defaults
--
local defaults = {
	global = {
		window = {
			x = 0,
			y = 0,
			point = "CENTER",
			relativePoint = "CENTER",
			width = 500,
			height = 300
		}
	}
}

function AspireML:OnInitialize()

	-- version
	self.VERSION = "r" .. tonumber(string.match("$Revision: 44 $", "(%d+)") or 1)	

	self.bids = {}
	self.bidsopen = false
	self.biditem = {}
	self.officers = {}
	self.masterlooter = false
	self.shortcut = nil

	-- setup whisper filter
	self.IGNOREWHISPERS = {}
	self.PLAYERNAME = UnitName("player");
	
	-- register command
	self:RegisterChatCommand( "aml", "SlashCommand" );
	
	-- DB
	self.db = LibStub("AceDB-3.0"):New("AspireMLDB", defaults)
	
end

function AspireML:OnEnable()
	self:RegisterEvent( "RAID_ROSTER_UPDATE", "UpdateRaid" )
end

function AspireML:OnDisable()
    -- Called when the addon is disabled
	--self:Print( "Disabled" );
end


-- gather all promoted people and the masterlooter
function AspireML:UpdateRaid( event, arg1, arg2 )
	
	-- reset current table
	for index, officer in pairs( self.officers ) do self.officers[index] = nil end
	
	-- GetGuildInfo
	local members = GetNumRaidMembers();
	
	for i = 1, members do
	
		-- Get raid member info
		local name, rank, subgroup, level, class, fileName, zone, online, isDead, role, isML = GetRaidRosterInfo(i)

		-- member is raid assist or raidleader
		if rank > 0 or isML then
		
			local entry = {}
			entry["player"] = name
			entry["raidid"] = "raid"..i
			entry["rank"] = rank
			
			table.insert( self.officers, entry )
						
		end
		
		if UnitIsUnit( "player", "raid" .. i ) then			
			self.masterlooter = isML
		end
	
	end	
	
end


function AspireML:SlashCommand( args )
	
	local command = string.split(' ', args):lower() or args:lower()		
	local argument = string.sub( args, string.len( command ) + 2 )
		
	if command == "bid" or command == "b" or command == "start" then
		AspireML:SendMessage( "AspireML_StartBid", argument )
	
	elseif command == "test" then
		local name, link = GetItemInfo( "52025" )
		AspireML:SendMessage( "AspireML_StartBid", link )
	
	elseif command == "list" then
		AspireML:SendMessage( "AspireML_ListBids" )
	
	elseif command == "roll" then
		AspireML:SendMessage( "AspireML_StartRoll", argument )
	
	elseif command == "rr" or command == "raidroll" then
		AspireML:SendMessage( "AspireML_StartRaidRoll", argument )
	
	elseif command == "close" then
		AspireML:SendMessage( "AspireML_CloseBid" )
	
	elseif command == "mule" then
		if not argument or argument == "" then
			self.shortcut = nil
			self:Print("Mule shortcut has been reset.")
		else
			local name = string.upper(string.sub(argument, 1, 1))..string.lower(string.sub(argument, 2))
			self.shortcut = name
			self:Print(("Mule shortcut has been set to: %s"):format(name))
		end
	
	elseif command == "show" then
	
		if not AspireML.biditem then
			self:Print( "No bid or roll active at the moment." );
		else
			BidsGui:ShowFrame()
		end
	
	elseif command == "help" or command == "" then
		self:Print( "==== AspireML (" .. self.VERSION .. ") ====" );
		self:Print( "Available options:" );
		self:Print( "   /aml bid [item]" );
		self:Print( "   /aml roll [item]" );
		self:Print( "   /aml rr [item]" );
		self:Print( "   /aml show" );
		self:Print( "   /aml list" );
		self:Print( "   /aml close" );
		
	else
		self:Print( "Type '/aml help' for available options" );
	
	end
	
end

--
-- Looting
--

StaticPopupDialogs["AML_GIVELOOT"] = {
	text = TEXT("Handout %s to %s?"),
	button1 = TEXT(ACCEPT),
	button2 = TEXT(CANCEL),
	OnAccept = function(self, data, data2)
		AspireML:Print(("Looting %s to %s."):format(data, data2));
		AspireML:Handout(data, data2, true)
	end,
	OnCancel = function()
		AspireML:Print("Cancelled.");
	end,
	timeout = 0,
	whileDead = 1,
};

-- ITEM MUST BE ITEM LINK, PLAYER MUST BE CAPITALIZED PLAYER NAME (I.E EXACT RETURN FROM UnitName())
function AspireML:Handout(item, player, confirmed)
	if not confirmed then
		if not item or not player then
			error("Error: AML Handout function requires arguments to both item and player")
			return nil
		end
		local lootdialog = StaticPopup_Show("AML_GIVELOOT", item, player);
		if(lootdialog) then
			lootdialog.data = item
			lootdialog.data2 = player
		end
	else
		-- Init loot process
		AspireML.HandoutLoot:LootToPlayer(item, player)
	end
end


--
-- Right click menu... Can only initialize it like this for some reason
--
local function AspireML_LootWindowInit()
	local info;
	-- add buttons to masterloot menu
	if (UIDROPDOWNMENU_MENU_LEVEL==1) then
		info = {};
		info.text = "Aspire ML:";
		info.notCheckable = 1;
		info.isTitle = 1;
		UIDropDownMenu_AddButton(info);
	
		info = {};
		info.notCheckable = 1;
		info.text = "Start bidding";
		info.func = function()
				local link = GetLootSlotLink(LootFrame.selectedSlot)
				assert(link, "ERROR: Could not retrieve item info for selected slot")
				AspireML:SendMessage("AspireML_StartBid", link);
			end
		UIDropDownMenu_AddButton(info);	
	
		info = {};
		info.text = "Raid roll";
		info.notCheckable = 1;
		info.func = function()
				local link = GetLootSlotLink(LootFrame.selectedSlot)
				assert(link, "ERROR: Could not retrieve item info for selected slot")
				AspireML:SendMessage("AspireML_StartRaidRoll", link);
			end
		UIDropDownMenu_AddButton(info);	
		
		info = {};
		info.text = "Players roll";
		info.notCheckable = 1;
		info.func = function()
				local link = GetLootSlotLink(LootFrame.selectedSlot)
				assert(link, "ERROR: Could not retrieve item info for selected slot")
				AspireML:SendMessage("AspireML_StartRoll", link);
			end
		UIDropDownMenu_AddButton(info);
		
		if(AspireML.shortcut) then
			info = {}
			info.text = ("Give to %s"):format(AspireML.shortcut);
			info.notCheckable = 1;
			info.func = function()
					local link = GetLootSlotLink(LootFrame.selectedSlot)
					assert(link, "ERROR: Could not retrieve item info for selected slot")
					AspireML:Handout(link, AspireML.shortcut)
				end
			UIDropDownMenu_AddButton(info);
		end
		
	end
	
	-- continue to initialize blizzard masterloot menu
	GroupLootDropDown_Initialize();
end

UIDropDownMenu_Initialize(GroupLootDropDown, AspireML_LootWindowInit, "MENU")